<?php

namespace App\Models;

use App\Exceptions\ApiErrorException;
use App\Util\ArrayUtil;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class GoodsRentSpec extends baseModel
{
    const KEY = 'spec_id';
    const TABLE = 'sp_goods_rent_spec';

    protected $table = self::TABLE;
    protected $primaryKey = self::KEY;
    protected $connection = 'mysql';

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'update_time';

    protected $guarded = [];

    protected $casts = [
        'create_time' => 'datetime:Y-m-d H:i:s',
        'update_time' => 'datetime:Y-m-d H:i:s',
    ];

    /**
     * 验证规格值是否合法
     * @param array $specList
     */
    public static function checkSpecData(array $specList)
    {
        $specNames = ArrayUtil::getArrayColumn($specList, 'spec_name');
        if (count($specList) != count(array_unique($specNames))) {
           throw new ApiErrorException('很抱歉，不能存在重复的规格组');
        }
        foreach ($specList as $item) {
            $values = ArrayUtil::getArrayColumn($item['valueList'], 'spec_value');
            if (count($item['valueList']) != count(array_unique($values))) {
                throw new ApiErrorException('很抱歉，不能存在重复的规格值');
            }
        }
    }

    /**
     * 根据规格值计算能生成的SKU总量
     * @param array $specList
     * @return int
     */
    public static function calcSkuListTotal(array $specList): int
    {
        $total = 1;
        foreach ($specList as $item) {
            $total *= \count($item['valueList']);
        }
        return $total;
    }

    /**
     * 规格组写入数据库并生成id
     * 此时的$specList是用户端传来的
     * @param array $specList
     */
    public static function getNewSpecList(array $specList)
    {
        // 遍历整理新的规格集
        foreach ($specList as $key => &$item) {
                // 规格名不存在的新增记录
                $result = static::add($item);
                $item['spec_id'] = $result['spec_id'];
            // 规格值写入数据库并生成id
            $item['valueList'] = GoodsRentSpecValue::getNewValueList((int)$item['spec_id'], $item['valueList']);
        }
        return $specList;
    }

    /**
     * 根据规格组名称集获取列表
     * @param array $names
     *
     */
    private static function getListByNames(array $names)
    {
        return (new static)->where('spec_name', 'in', $names)
            ->select();
    }

    /**
     * 新增规格组记录
     * @param array $item
     */
    private static function add(array $item)
    {
        return self::create([
            'is_image' => isset($item['is_image'])?$item['is_image']:0,
            'spec_name' => $item['spec_name'],
        ]);
    }
}
